package com.codeying.servlet;

import com.codeying.servlet.AbsServlet;
import com.codeying.entity.*;
import com.codeying.utils.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 用于登陆的Servlet
 */
@WebServlet("/login")
public class LoginServlet extends AbsServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //设置编码，否则从前端获取参数乱码
        req.setCharacterEncoding("utf-8");

        //登录开始
        LoginUser loginUser;
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String usertype = req.getParameter("usertype");
        if(usertype.equals("admin")) {
            loginUser = adminService.login(username,password);
            if (loginUser != null) {
                req.getSession().setAttribute("user", loginUser);
                req.getSession().setAttribute("role", "admin");
                resp.sendRedirect(req.getContextPath() + "/hello");
                return;
            }
        }
        if(usertype.equals("user")) {
            loginUser = userService.login(username,password);
            if (loginUser != null) {
                req.getSession().setAttribute("user", loginUser);
                req.getSession().setAttribute("role", "user");
                resp.sendRedirect(req.getContextPath() + "/hello");
                return;
            }
        }
        //登陆失败，就重新登陆
        req.setAttribute("message","账号密码有误，登陆失败");
        req.getRequestDispatcher("/login.jsp").forward(req,resp);

    }

}

